<!DOCTYPE html>
<!--suppress ALL -->
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>averageBy(平均)</title>
</head>
<body>
<h4>
    Returns the average of an array, after mapping each element to a value using the provided function.
    Use Array.map() to map each element to the value returned by fn,
    Array.reduce() to add each value to an accumulator,
    initialized with a value of 0, divide by the length of the array.
</h4>
<h4>
    Array.map(function action) 方法返回一个新数组，数组中的元素为原始数组元素调用action函数处理后的值
    reduce(function callback,obj) 方法把函数返回值和序列的下一个元素做callback函数新的参数并再一次回调，最终计算为一个值
    obj为callback函数的第一个参数的默认值
    reduce() 可以作为一个高阶函数，用于函数的 compose
    注意: reduce() 对于空数组是不会执行回调函数的
</h4>
<script type="text/javascript">
    const averageBy = (arr, fn) =>
        arr.map(typeof fn === "function" ? fn : val => val[fn]).
        reduce((acc, val) => acc + val, 0) / arr.length;
    console.log( averageBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n)); //5
    console.log( averageBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n')); //5
</script>
</body>
</html>